package com.widget;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ApkParser implements ParseStreaming {

	private int count;
	private int track = 0;
	//private Handler mMsgHandler;
	private Handler mContext;
	
	//rsync: failed to connect to [0-9]+.[0-9]+.[0-9]+.[0-9]+: Connection refused
	//rsync: failed to connect to [0-9]+.[0-9]+.[0-9]+.[0-9]+: Network is unreachable
	//rsync: failed to connect to [0-9]+.[0-9]+.[0-9]+.[0-9]+: Connection timed out
	//rsync error: error in socket IO
	@Override
	public int parseString(String content) {
		Pattern end = Pattern.compile("total size is [0-9]+  speedup is [0-9]+.[0-9]+");
		Pattern cRefused = Pattern.compile("rsync: failed to connect to [0-9]+.[0-9]+.[0-9]+.[0-9]+: Connection refused");
		Pattern nUnreachable = Pattern.compile("rsync: failed to connect to [0-9]+.[0-9]+.[0-9]+.[0-9]+: Network is unreachable");
		Pattern cTimeOut = Pattern.compile("rsync: failed to connect to [0-9]+.[0-9]+.[0-9]+.[0-9]+: Connection timed out");
		Pattern error = Pattern.compile("rsync error: error in socket IO");
		
		Matcher endM = end.matcher(content);
		Matcher cRefusedM = cRefused.matcher(content);
		Matcher nUnreachableM = nUnreachable.matcher(content);
		Matcher cTimeOutM = cTimeOut.matcher(content);
		Matcher errorM = error.matcher(content);
		
		//Check for end of successfull synchronization
		if(endM.find()){
			track++;
			Log.d("APK parser","End of Rsync");
		}
		if(track == count)
		{
			Log.d("APK parser","Finalization of Rsync");
			mContext.sendEmptyMessage(SYNCED);
			track = 0;
			return 0;
		}
		
		if(cRefusedM.find()){
			mContext.sendEmptyMessage(REFUSED);
		}
		if(nUnreachableM.find()) {
			mContext.sendEmptyMessage(UNREACHABLE);
		}
		if(cTimeOutM.find()) {
			mContext.sendEmptyMessage(TIMEOUT);
		}
		if(errorM.find()) {
			mContext.sendEmptyMessage(ERROR);
			return 0;
		}
		return 1;
	}
	
	@Override
	public void endMatcher(int n,Handler c) {
		count=n;
		mContext =  c;	
	}

	

}
